#include "intelHEX.h"

bool checkCRC(char line[]) {
	uint8_t value;
	uint8_t summed = 0;
	uint16_t length = 0;

	length = strlen(line);
	if(length > 0 ) {
		if(line[0] == ':'){
			for (uint8_t i = 1; i < length; i+=2) { // start after the :
				value = decodeHex(line[i],line[i+1]);
				summed+=value;
			}

			if (summed==0){
				return(true);
			}
		}
	}
	return(false);
}

uint8_t hexDigit(uint8_t hex){
	if(hex > 96){
		hex -= (97-10);
	} else if(hex > 64){
		hex -= (65-10);
	} else if(hex > 47) {
		hex -= (48);
	}
	if (hex < 16) {
		return (hex);
	} else {
		return(0);
	}
}

uint8_t decodeHex(uint8_t MSD, uint8_t LSD) {
	uint8_t value;
	value = (hexDigit(MSD)<<4)+hexDigit(LSD);
	return (value);
}


hexCommand parseHexCommand(uint8_t line[], uint8_t data[]) {
	hexCommand retVal;

	retVal.byteCount = decodeHex(line[1],line[2]);
	retVal.startAddress = decodeHex(line[3],line[4])<<8;
	retVal.startAddress += decodeHex(line[5],line[6]);
	retVal.recordType = decodeHex(line[7],line[8]);

	if (retVal.recordType == 0) { //execute a plain data record
		// decode the data section of the packet
		for (uint8_t i = 0; i < retVal.byteCount; i++) {

			data[i] = decodeHex(line[(i*2)+9],line[(i*2)+10]);
		}
	}

	return(retVal);

}
